﻿using Newtonsoft.Json;
using Pay.Window.Data.Dto;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Window.Data.Utilitys
{
    public class DataHelper
    {
        private static readonly string DATA_DIR = $"{AppDomain.CurrentDomain.BaseDirectory}data\\";
        private static readonly string DATA_EXNAME = "payd";
        private static readonly string DATA_FILE = $"{AppDomain.CurrentDomain.BaseDirectory}data\\{{0}}.{DATA_EXNAME}";
        private static Dictionary<string, IList<WindowOrderInput>> AllOrders { get; set; }
        private const int ORDER_COUNT_MAX = 100;
        /// <summary>
        /// 初始化数据
        /// </summary>
        public static void Init()
        {
            CreateDataDir();

            AllOrders = new Dictionary<string, IList<WindowOrderInput>>();

            var files = Directory.GetFiles(DATA_DIR);
            foreach (var filename in files)
            {
                var exname = filename.Substring(filename.LastIndexOf(".") + 1); // 得到后缀名
                var systemAccount = filename.Substring(filename.LastIndexOf("\\") + 1).Split('.')[0]; // 获取系统账户名
                if (exname == DATA_EXNAME)
                {
                    AllOrders.Add(systemAccount, GetFileData(systemAccount));
                }
            }
        }

        /// <summary>
        /// 保存数据到磁盘
        /// </summary>
        /// <param name="systemAccount"></param>
        /// <param name="orders"></param>
        public static void Save(string systemAccount)
        {
            try
            {
                CreateDataDir();

                CreateDataFile(systemAccount);

                var filename = string.Format(DATA_FILE, systemAccount);
                File.WriteAllText(filename, JsonConvert.SerializeObject(GetData(systemAccount)));
            }
            catch
            {
                // throw new Exception($"{systemAccount}数据写入失败");
            }
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="systemAccount"></param>
        /// <param name="order"></param>
        public static void AddData(string systemAccount, WindowOrderInput order)
        {
            if (!AllOrders.ContainsKey(systemAccount))
            {
                AllOrders.Add(systemAccount, new List<WindowOrderInput>());
            }
            AllOrders[systemAccount].Add(order);

            if (AllOrders[systemAccount].Count > ORDER_COUNT_MAX)
            {
                AllOrders[systemAccount] = AllOrders[systemAccount].OrderByDescending(s => s.CreateTime).Take(ORDER_COUNT_MAX).ToList();
            }
        }

        /// <summary>
        /// 获取内存数据
        /// </summary>
        /// <param name="systemAccount"></param>
        /// <returns></returns>
        public static IList<WindowOrderInput> GetData(string systemAccount)
        {
            if (AllOrders.ContainsKey(systemAccount))
            {
                return AllOrders[systemAccount];
            }
            return new List<WindowOrderInput>();
        }

        public static void UpdateDataSubmit(string systemAccount)
        {
            if (AllOrders.ContainsKey(systemAccount))
            {
                foreach (var o in AllOrders[systemAccount].Where(s => s.IsSubmit == false))
                {
                    o.IsSubmit = true;
                }
            }
        }

        /// <summary>
        /// 获取文件数据
        /// </summary>
        /// <param name="systemAccount"></param>
        /// <returns></returns>
        private static IList<WindowOrderInput> GetFileData(string systemAccount)
        {
            var filename = string.Format(DATA_FILE, systemAccount);
            try
            {
                var dataStr = File.ReadAllText(filename);
                // 保证始终是实例化的数据返回
                return JsonConvert.DeserializeObject<IList<WindowOrderInput>>(string.IsNullOrEmpty(dataStr) ? "[]" : dataStr);
            }
            catch
            {
                // throw new Exception($"{systemAccount}数据解析失败");
                // 一旦数据解析失败,清空所有记录
                File.WriteAllText(filename, "");
            }
            return new List<WindowOrderInput>();
        }

        private static void CreateDataFile(string systemAccount)
        {
            var filename = string.Format(DATA_FILE, systemAccount);
            if (!File.Exists(filename))
            {
                using (File.Create(filename))
                {

                }
            }
        }

        private static void CreateDataDir()
        {
            if (!Directory.Exists(DATA_DIR))
            {
                Directory.CreateDirectory(DATA_DIR);
            }
        }
    }
}
